/*
* @Author: 窦子滨<zibin_5257@163.com>
* @Date: 2019-04-10
 */
package TcpPack

import (
	"bytes"
	"strconv"
	"time"
)

//登录业务

func (p *PackBase) login(conn *HpCharge) {
	//业务数据解码
	info := new(LoginPack)
	info.Unpack(bytes.NewReader(p.Data))
	Log.Info("[%s][%d][充电桩登录0x02处理][业务数据：%+v]", conn.ConnId, p.DeviceId, info)
	conn.chanLogin<-1

	//读取充电桩基础数据
	_, ok := Piles[strconv.FormatInt(int64(p.DeviceId), 10)]

	var confirm int8

	if !ok {
		confirm = 0
		Log.Info("[%s][%d][登录失败][该充电桩未在定义列表中]", conn.ConnId, p.DeviceId)
	} else {
		//建立充电桩编号与连接序号之间的关系
		conn.SetConnDeviceID(p.DeviceId)

		Log.Info("[%s][%d][登录成功][登录成功]", conn.ConnId, p.DeviceId)
		go Test0x05(conn)

		go func() {
			time.Sleep(time.Duration(150)*time.Second)
			Log.Info("[%s][%d][请插入充电枪][]",conn.ConnId,conn.DeviceId)
		}()

		//登录成功后10s发起主动对时
		go func(conn *HpCharge) {
			//连接成功后 10s发起对时请求
			time.Sleep(time.Duration(10) * time.Second)
			conn.sendServerTime()
			//发送对时报文后 5s内未收到回复则输出错误
			select {
			case <-time.After(time.Duration(5) * time.Second):
				Log.Error("[%s][%d][失败：主站对时0x08失败][未在规定时间内回复]",conn.ConnId,conn.DeviceId)
			case <-conn.chanTime:
				Log.Info("[%s][%d][通过：主站对时0x08成功][]",conn.ConnId,conn.DeviceId)
			case <-conn.ctx.Done():
				Log.Info("[%s][%d][主站对时0x08检测终止][]",conn.ConnId,conn.DeviceId)
			}
		}(conn)

		//实时数据检测
		go func(conn *HpCharge) {
		ForEnd:
			for {
				select {
				case <-time.After(time.Duration(35) * time.Second):
					Log.Error("[%s][%d][失败：主动上传实时数据0x14检测超时][未在30秒上传0x14报文]",conn.ConnId,conn.DeviceId)
				case <-conn.chanReal:
					Log.Info("[%s][%d][通过：主动上传实时数据0x14][]",conn.ConnId,conn.DeviceId)
				case <-conn.ctx.Done():
					Log.Info("[%s][%d][主动上传实时数据0x14检测终止][]",conn.ConnId,conn.DeviceId)
					break ForEnd
				}
			}
		}(conn)

		//主动获取浮点费率检测 0x41 需在2分钟内发送报文
		go func(conn *HpCharge) {
			select {
			case <-time.After(time.Duration(120) * time.Second):
				Log.Error("[%s][%d][失败：充电桩获取浮点费率0x41检测超时][未在连接成功后120秒内发送0x41报文]",conn.ConnId,conn.DeviceId)
			case <-conn.chan0x41:
				Log.Info("[%s][%d][通过：充电桩获取浮点费率0x41][在规定时间内发送0x41报文]",conn.ConnId,conn.DeviceId)
			case <-conn.ctx.Done():
				Log.Info("[%s][%d][充电桩获取浮点费率0x41检测终止][]",conn.ConnId,conn.DeviceId)
			}
		}(conn)

		confirm = 1
	}

	//登录返回数据
	write := &LoginReplyPack{
		Confirm: confirm,
		Version: info.Version,
	}

	buf := new(bytes.Buffer)
	write.Pack(buf)

	f := PackAll(p.DeviceId, p.Direct, "0", p.GunId, 1, buf.Bytes())

	conn.WriteData(f)
}
